package com.qinghua.blog.service;

import com.qinghua.blog.NoFoundException;
import com.qinghua.blog.dao.TagRepository;
import com.qinghua.blog.po.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TagServiceImpl implements TagService{

    @Autowired
    TagRepository tagRepository;

    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        Tag save = tagRepository.save(tag);
        return save;
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        Tag one = tagRepository.getOne(id);
        return one;
    }

    @Transactional
    @Override
    public Tag getTagByName(String name) {
        Tag tagByName = tagRepository.findTagByName(name);
        return tagByName;
    }

    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {

        Page<Tag> all = tagRepository.findAll(pageable);
        return all;
    }

    @Transactional
    @Override
    public List<Tag> findAll() {
        List<Tag> all = tagRepository.findAll();
        return all;
    }

    @Transactional
    @Override
    public List<Tag> getTagByTop(Integer size) {
        Sort sort=Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable= PageRequest.of(0,size,sort);
        return tagRepository.findByTop(pageable);
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag one = tagRepository.getOne(id);
        if(one==null){
            throw new NoFoundException();
        }
        BeanUtils.copyProperties(tag,one);
        Tag save = tagRepository.save(one);
        return save;
    }

    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }
}
